var express 		= require('express');    
var mysql   		= require('mysql');
var config  		= require('../config.json');
var sqlconfig 		= config.mysql;
var router  		= express.Router();
var pool    		= mysql.createPool(sqlconfig);


/*
  Name: data
  Args:
	data:data to be return
	res :response to write data
  Return : 
	Valid String for Client to use
  Description：
	  Return the valid  Data String to client if there is no error
*/

function data(data,res)
{
	console.log("LOG:RESPONSE:"+data);
	return res.end(JSON.stringify({err:0,response:data}));
}

/*
  Name: error
  Args:
	res:response to write err
	err:error message to return
	errcode: description of an error
  Return : 
	Valid String for Client to use
  Description：
	Return the error message to the client 
*/

function error(err,errcode,res)
{
	console.log("LOG:ERROR:"+errcode);
	return res.end(JSON.stringify({err : err,errcode : errcode}));
}

/*
  Name: BeforeAspect 
  Args: 
	request:Object
  Return: 
	data return from this aspect
  Description:
	preprocessor
*/

function BeforeAspect(request)
{
	
	console.log("LOG:REQUEST:"+JSON.stringify(request));
	return request;
}


/*
    Name: Notification_Get_All 
    Args: 
	    req:JSON :[ args] arguments of this query????????
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	get all notification
*/

function Notification_Get_All(req,res,next)
{
  
	var query="SELECT n.*,notification_type.notification_type_name FROM (SELECT * FROM notification) n LEFT JOIN notification_type ON n.notification_type_id = notification_type.notification_type_id ORDER BY notification_time DESC;";
	try
	{
		var query_args = [];
		pool.query(query,query_args,
			function(err,rows,fields)
			{
				if(err)
				{
					error(300,err,res);
				    return;
				}
				data(rows,res);
				return;
			});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
}



/*
    Name: Notification_Check
    Args: 
	    req:JSON :[ args] arguments of this query
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	    check specific notification
*/

function Notification_Check (req,res,next) 
{

	var query="SELECT n.*,notification_type.notification_type_name FROM (SELECT * FROM notification WHERE notification_id = ?) n LEFT JOIN notification_type ON n.notification_type_id = notification_type.notification_type_id ORDER BY notification_time DESC;";
	
	try
	{

		var args = BeforeAspect(req.body);

		var query_args = [];
		if(typeof(args['notification_id']) != 'number' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{
			query_args.push(args['notification_id']);
		}

		
		pool.query(query,query_args,
			function(err,rows,fields)
			{
				if(err)
				{
					error(500,err,res);
					return;
				}
				else
				{
					data(rows,res);
				}
			return;
			});

	}catch(err)
	{
        error( -1 ,err,res);
	}
	return;
}


/*
    Name: Picture_Get_All 
    Args: 
	    req:JSON :[ args] arguments of this query????????
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	get pictures of specific notification
*/
function Picture_Get_All(req,res,next)
{
	var query = "select * from picture where notification_id = ?;";
	try
	{
		var args = BeforeAspect(req.body);

		var query_args = [];
		if(typeof(args['notification_id']) != 'number' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{
			query_args.push(args['notification_id']);
		}

		pool.query(query,query_args,
			function(err,rows,fields)
			{
				if(err)
				{
					error(300,err,res);
				    return;
				}
				else
				{
					data(rows,res);
					return;

				}

			});

	}catch(err)
	{
  		error(-1,err,res);
	}

	return;
}


/*
    Name: Notification_Update
    Args: 
	    req:JSON :[ args] arguments of this query
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	    Update specific notification
*/
function Notification_Update(req,res,next)
{
	var query  = "UPDATE notification set notification_name = ?,notification_time = ? WHERE notification_id= ?" ;
    try
    {
		var args = BeforeAspect(req.body);
		var query_args = [];

        if(typeof(args['notification_id']) != 'number' 
		  || typeof(args['notification_name']) != 'string' 
		//  || typeof(args['notification_content']) != 'string' 
		  || typeof(args['notification_time']) != 'string' 
		  )
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{

			query_args.push(args['notification_name']);
			//query_args.push(args['notification_content']);
			query_args.push(args['notification_time']);
			query_args.push(args['notification_id']);
        }

        pool.query(query,query_args,
        	function(err,rows,fields)
        	{
			if(rows['affectedRows'] == 1 )
			{
				if(err)
                		{
					error(500,err,res);
					return;
                		}
				if(rows['changedRows'] == 1)
				{
					data(0,res);
				}
				else
				{
					error(301,"Nothing Changed!",res);
				}
			}
			else
			{
				error(401,"Invalid Argument",res);
			}
			return;
        	});


    }catch(err)
    {
    	error(-1,err,res);
    }
	return;
}

/*
    Name: Notification_Type_Update
    Args: 
	    req:JSON :[ args] arguments of this query
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	    Update notification_type ofspecific notification
*/
function Notification_Type_Update(req,res,next)
{
	var query = "UPDATE notification set notification_type_id= ? WHERE notification_id= ?";
	 try
    {
		var args = BeforeAspect(req.body);
		var query_args = [];

		if(typeof(args['notification_id']) != 'number' 
			|| typeof(args['notification_type_id']) != 'number' 
		)
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{
			query_args.push(args['notification_type_id']);
			query_args.push(args['notification_id']);
		}

		pool.query(query,query_args,
        	function(err,rows,fields)
        	{
			if(rows['affectedRows'] == 1 )
			{
				if(err)
                		{
					error(500,err,res);
					return;
                		}
				if(rows['changedRows'] == 1)
				{
					data(0,res);
				}
				else
				{
					error(301,"Nothing Changed!",res);
				}
			}
			else
			{
				error(401,"Invalid Argument",res);
			}
        	});
	}catch(err)
	{
		error(-1,err,res);
	}
return;
}


/*
    Name: Notification_Picture_Update
    Args: 
	    req:JSON :[ args] arguments of this query
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	    Update picture_path ofspecific notification
*/
function Notification_Picture_Update(req,res,next)
{
	var query = "UPDATE picture set picture_path= '?' WHERE picture_id= ?";
	 try
    {
    	var args = BeforeAspect(req.body);
        if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}
	
		if(typeof(req.session.user_type)!='teacher')    //对公告的权限设置
		{
			error(403,'permission denied',res);
			return;
		}

         var query_args = [];

        if(typeof(args['picture_id']) != 'number' 
		  || typeof(args['picture_path']) != 'string' 
		  )
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{
			query_args.push(args['picture_path']);
			query_args.push(args['picture_id']);
        }

        pool.query(query,query_args,
        	function(err,rows,fields)
        	{
                if(err)
                {
					error(500,err,res);
					return;
                }
                else
                {
                	date(rows,res);
                }
                return;
        	});


    }catch(err)
    {
    	error(-1,err,res);
    }
return;
}

/*
    Name: Notification_Delete
    Args: 
	    req:JSON :[ args] arguments of this query
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	    delete specific notification
*/

function Notification_Delete(req,res,next)
{
	query= "DELETE FROM notification WHERE notification_id = ?";
	try
	{
		var args = BeforeAspect(req.body);
		var query_args = [];

		if(typeof(args['notification_id']) != 'number' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		console.log("OK!");
		query_args.push(args['notification_id'])

		pool.query(query,query_args,
		function(err,rows,fields)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				if(rows['changedRows'] == 1)
					return data(0,res);
				else
				{
					return error(302,"Nothing Deleted",res);
				}
				data(rows,res)
			}
			return;
		});
	}catch(err)
	{
		error(-1,err,res);
	}
	return;
}

/*
    Name: Picture_Delete
    Args: 
	    req:JSON :[ args] arguments of this query
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	    delete pictures of specific notification
*/

function Picture_Delete(req,res,next)
{
	query= "delete*from npicture where notification_id = ?";
	try
	{
		var args = BeforeAspect(req.body);
		if(typeof(req.session.user != object))
		{
			error(402,'Login First',res);
			return;
		}
		if(typeof(req.session.user_type) !=teacher)
		{
			error(403,'permission denied',res);
		}
        
        var query_args = [];

        if(typeof(args['notification_id']) != 'number' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}

		pool.query(query,query_args,
			function(err,rows,fields)
			{
				if(err)
				{
					error(500,err,res);
					return;
				}
				else
				{
					data(rows,res)
				}
				return;
			});


	}catch(err)
	{
		error(-1,err,res);
	}
	return;
}




/*
    Name: Notification_Insert
    Args: 
	    req:JSON :[ args] arguments of this query
	    res: response to write data/error
	    next:
    Return: 
     	None
    Description:
	    add specific notification
*/


function Notification_Insert(req,res,next)
{
    var query = "INSERT INTO notification SET ?";
    
    try
    {

        var args = BeforeAspect(req.body);

        if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}

		var query_args = {};
		if(  typeof(args['notification_type_id']) != 'number' 
			|| typeof(args['notification_name']) != 'string' 
			|| typeof(args['notification_content']) != 'string' 
			|| typeof(args['notification_time']) != 'number' 
			)
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{
			query_args['notification_type_id']= args['notification_type_id'];
			query_args['notification_name']	= args['notification_name'];
			query_args['notification_content']	= args['notification_content'];
			query_args['notification_time']= args['notification_time'];
		}

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
                //console.log(result.insertId);
                //var query = "INSERT INTO picture SET ?"/
                 //图片


			}
			return;
		});


    }
	catch(err)
	{
        error(-1,err,res);
	}
    
	return;
}



//Register '/' GET router
router.get('/', function(req, res, next) 
{
  data({},res);
});

//Register all routers 
var functions = {	 "/Notification_All"     	: Notification_Get_All
			,"/Notification_Check"	: Notification_Check
			,"/Picture_Get_All": Picture_Get_All
			
			,"/Notification_Update"     	: Notification_Update
			,"/Notification_Type_Update"	: Notification_Type_Update
			,"/Notification_Picture_Update" : Notification_Picture_Update
				
			,"/Notification_Delete" 	: Notification_Delete
			,"/Picture_Delete" 	: Picture_Delete
			,"/Notification_Insert" 	: Notification_Insert
			}

for(var i in functions) 
{
	console.log("FUNCTION_LOADED(notification):"+i);
	router.post(i, functions[i]);
}

module.exports = router;
